package kr.co.bettersoft.pushchat.fragment;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import kr.co.bettersoft.pushchat.activity.PullToRefreshListView;
import kr.co.bettersoft.pushchat.activity.MemberInfoActivity;
import kr.co.bettersoft.pushchat.activity.PullToRefreshListView.OnRefreshListener;
import kr.co.bettersoft.pushchat.activity.R;
import kr.co.bettersoft.pushchat.activity.SearchMemberActivity;
import kr.co.bettersoft.pushchat.adapter.PushChatFriendListAdapter;
import kr.co.bettersoft.pushchat.adapter.PushChatMemberListAdapter;
import kr.co.bettersoft.pushchat.common.CommonConstant;
import kr.co.bettersoft.pushchat.common.CommonUtil;
import kr.co.bettersoft.pushchat.common.PushChatRest;
import kr.co.bettersoft.pushchat.domain.PushChatFriend;
import kr.co.bettersoft.pushchat.domain.PushChatMember;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

/**
 * MemberListFragment
 *  멤버 리스트 화면
 *   상단 타이틀 : 멤버 / 왼쪽에 친구목록 버튼 / 오른쪽에 친구 검색 버튼
 *   목록 - 왼쪽에 섬네일이미지(없으면 기본 이미지) 위에 이름(아이디), 아래에 내소개가 한줄로 나오고 화면 끝에서 ... 처리
 *   친구리스트 모드로 하면 - 전체가 아닌 친구 목록만. 상단 타이틀 : 친구 / 왼쪽에 멤버 버튼(전체 멤버)
 *   
 * @author blue
 *
 */
public class MemberListFragment extends Fragment{			
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// 변수

	String TAG = "MemberListFragment";

	//		public final int SELECT_MEMBER_LIST = 101;  		// 멤버 목록을 가져온다.		// selectMemberList
	public final int SELECT_SEARCH_MEMBER_LIST = 102;  // 검색한 멤버 목록을 가져온다. 	// selectSearchMemberList  + 일반 멤버 목록도 이거로 호출.
	public final int SELECT_FRIEND_LIST = 103;  		// 친구 목록을 가져온다. 	// selectFriendList

	//		public final int GET_WAIT_PERSON_NUMBER = 601;  // 대기목록을 가져오기 전에 현재 대기중인 팀 수를 가져온다. 0명이면 안가져옴
	//		public final int GET_WAIT_LIST = 602; 			// 대기 목록을 가져온다. 그리고 입장모드일 경우 위에서 가져온 totalCount 정보에 따라 입장 처리도 함.
	////		public final int SELECT_USER_TOTAL_COUNT = 603; 	// 최초 실행. (오늘) 총 대기 인원 숫자를 가져 온다. 
	//		public final int SELECT_REGISTER_TEAM_AND_USER = 604; 	//  최초 실행. 오늘 총 등록 팀수, 인원 수를 가져온다. 
	//		
	//		public final int ENTRANCE_NEXT_PERSON = 605; 			// 다음고객 입장		
	//		public final int UPDATE_USER_ADMISSIONYN_AND_USER_NEXTTURNYN = 606; 			// 다음고객 입장 (대기 2인 이상)
	//		public final int ENTRANCE_OTHER_PERSON = 607; 			// 우선 입장

	SharedPreferences sharedPrefCustom;	// 공용 프립스	
	String userId;						// 사용자 아이디

	// 프래그먼트 종료 여부. 종료된 경우 스레드 호출로 인한 에러를 방지하기 위함
	Boolean isFinished = false;

	// 서버 통신용
	static Boolean countOne = true;		// 한번에 한번만 통신 하도록
	PushChatRest pushChatRest;
	String callResult = "";
	JSONObject jsonObject;


	String resultStr;		// 요청 결과

	// 서버에서 받은 대기 인원 리스트 임시 저장
	int max = 0;

	// 검색용
	PushChatMember pushChatMemberParam;

	// 멤버 리스트
	List<PushChatMember> pushChatMemberEntriesFn;
	// 친구 리스트
	List<PushChatFriend> pushChatFriendEntriesFn;
	// adapter - 아답터는 전역으로 사용하는 곳도 있고, 아닌 곳도 있어서 공통성을 위해 전역으로 사용.
	private PushChatMemberListAdapter pushChatMemberListAdapter;		// 그리드뷰 사용할 아답터
	private PushChatFriendListAdapter pushChatFriendListAdapter;		// 그리드뷰 사용할 아답터

	// 화면 구성

	View mainMemberlistTitle_1;
	View mainMemberlistTitle_2;

	ImageButton mainMemberListFriendListBtn;		// 상단 친구보기 버튼
	Button mainMemberListMemberListBtn;		// 상단 전체멤버보기 버튼
	ImageButton mainMemberListMemberSearchBtn;		// 상단 멤버 검색 버튼

	ListView memberListView;
	View emptyView;				// 데이터 없음 뷰
	ProgressBar pb1;		// 중단 로딩 진행바

	// pull down refresh
	Boolean pullDownRefreshIng  = false;

	int screenMode = 0;		// 상세 화면 보는지 여부. 상세화면 보고 온 경우에는 리스트를 갱신해준다?		// screenMode 1 : 전체 목록. 2 : 친구목록. 3 전체목록. refresh필요. 4. 친구목록. refresh 필요


	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	// 핸들러
	Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			try{
				Bundle b = msg.getData();		

				if(b.getInt("showToast")==1){		// 화면에 토스트 띄우기
					Toast.makeText(getActivity(), b.getString("msg"), Toast.LENGTH_SHORT).show();
				}
				if(b.getInt("showAlert")==1){					 // 경고창 . 
					//
					new AlertDialog.Builder(returnThis())
					.setTitle(CommonConstant. alertTitle )                                        
					.setMessage(b.getString("msg"))
					.setIcon(R.drawable.ic_dialog_img)		
					.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							// 단순 확인 용도
						}})
						.setNegativeButton("", null).show();
				}
				if(b.getInt("showMemberList")==1){
					// 데이터를 화면에.. 
					if((pushChatMemberEntriesFn!=null)&&(pushChatMemberEntriesFn.size()>0)){
						setGriding();			// 항시 업뎃
						memberListView.setVisibility(View.VISIBLE);
						emptyView.setVisibility(View.GONE);
					}else{
						Log.d(TAG,"no data");
						memberListView.setEmptyView(emptyView);
						memberListView.setVisibility(View.GONE);
						emptyView.setVisibility(View.VISIBLE);
					}
				}
				if(b.getInt("showFriendList")==1){
					// 데이터를 화면에.. 
					if((pushChatFriendEntriesFn!=null)&&(pushChatFriendEntriesFn.size()>0)){
						setGriding2();			// 항시 업뎃
						memberListView.setVisibility(View.VISIBLE);
						emptyView.setVisibility(View.GONE);
					}else{
						Log.d(TAG,"no data");
						memberListView.setEmptyView(emptyView);
						memberListView.setVisibility(View.GONE);
						emptyView.setVisibility(View.VISIBLE);
					}
				}

				if(b.getInt("order")==1){
					// 프로그래스바 실행
					pb1.setVisibility(View.VISIBLE);
				}else if(b.getInt("order")==2){
					// 프로그래스바  종료
					pb1.setVisibility(View.GONE);
				}

				switch (msg.what)
				{
				case SELECT_SEARCH_MEMBER_LIST : 		// 검색한 멤버 목록을 가져온다. 	// selectSearchMemberList
					if(getActivity()!=null) {
						getActivity().runOnUiThread(new RunnableSelectSearchMemberList());
					}
					break;	
				case SELECT_FRIEND_LIST : 			// 친구 목록을 가져온다. 	// selectFriendList  RunnableSelectFriendList
					if(getActivity()!=null) {
						getActivity().runOnUiThread(new RunnableSelectFriendList());		// ## @@ 
					}
					break;	
				default : 
					break;
				}

			}catch(Exception e){
				e.printStackTrace();
			}
		}
	};

	/**
	 * setGriding
	 * 데이터를 화면에 세팅한다 - 멤버 목록
	 *
	 * @param 
	 * @param 
	 * @return 
	 */
	public void setGriding(){
		pushChatMemberListAdapter = new PushChatMemberListAdapter(getActivity(), pushChatMemberEntriesFn);
		memberListView.setAdapter(pushChatMemberListAdapter);

		// 클릭시 상세보기 페이지로
		memberListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {
				int memberRealPostion = 0;
				if(memberListView.getCount()==pushChatMemberEntriesFn.size()){	// 상단에 아무것도 없으므로 그냥 사용
					memberRealPostion = position;
				}else{
					memberRealPostion = position -1;		// 상단에 pull down refresh 영역 한칸 차지하고 있으므로 한칸 빼줌.
				}



				//					// screenMode 1 : 전체 목록. 2 : 친구목록. 3 전체목록. refresh필요. 4. 친구목록. refresh 필요
				screenMode = 3;
				Intent intent = new Intent(getActivity(), MemberInfoActivity.class);
				PushChatMember pushChatMemberParam =  pushChatMemberEntriesFn.get(memberRealPostion);
				intent.putExtra("memberId", pushChatMemberParam.getMemberId());							//
				startActivity(intent);
			}	
		});

		// item 롱클릭시 
		memberListView.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				if(memberListView.getCount()==pushChatMemberEntriesFn.size()){	// 상단에 아무것도 없으므로 그냥 사용
					//						firstEntrancePosition = arg2;
				}else{
					//						firstEntrancePosition = arg2 -1;		// 상단에 pull down refresh 영역 한칸 차지하고 있으므로 한칸 빼줌.
				}
				//					if(firstEntrancePosition!=0){		// 0 번째는 우선 입장 기능 x. 일반 입장o
				//						confirmAndEnterUser2();
				//					}else{
				//						confirmAndEnterUser();			// 0번째에게는 일반 입장창이라도 뜨게 함. (0번째만 안뜨니 이상해서)
				//					}
				return false;
			}
		});
	}

	/**
	 * setGriding2
	 * 데이터를 화면에 세팅한다 - 친구 목록
	 *
	 * @param 
	 * @param 
	 * @return 
	 */
	public void setGriding2(){
		pushChatFriendListAdapter = new PushChatFriendListAdapter(getActivity(), pushChatFriendEntriesFn);
		memberListView.setAdapter(pushChatFriendListAdapter);

		// 클릭시 상세보기 페이지로
		memberListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {

				int memberRealPostion = 0;
				if(memberListView.getCount()==pushChatFriendEntriesFn.size()){	// 상단에 아무것도 없으므로 그냥 사용
					memberRealPostion = position;
				}else{
					memberRealPostion = position -1;		// 상단에 pull down refresh 영역 한칸 차지하고 있으므로 한칸 빼줌.
				}

				screenMode = 4;
				Intent intent = new Intent(getActivity(), MemberInfoActivity.class);
				PushChatFriend pushChatFriendParam =  pushChatFriendEntriesFn.get(memberRealPostion);
				intent.putExtra("memberId", pushChatFriendParam.getMemberId());							//
				startActivity(intent);
			}	
		});
	}
	//		
	//		
	//	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//		
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		View view = inflater.inflate(R.layout.fragment_memberlist, null);

		pushChatRest = new PushChatRest();

		mainMemberlistTitle_1 = (View) view.findViewById(R.id.main_memberlist_title_1);	
		mainMemberlistTitle_2 = (View) view.findViewById(R.id.main_memberlist_title_2);	

		mainMemberListFriendListBtn = (ImageButton) view.findViewById(R.id.main_memberlist_friendlist_btn);
		mainMemberListMemberListBtn = (Button) view.findViewById(R.id.main_memberlist_memberlist_btn);
		mainMemberListMemberSearchBtn = (ImageButton) view.findViewById(R.id.main_memberlist_membersearch_btn);

		memberListView = (ListView) view.findViewById(R.id.member_list_view);		
		emptyView = view.findViewById(R.id.empty1);		// 데이터 없으면 '빈 페이지'(데이터 없음 메시지)표시
		pb1=(ProgressBar) view.findViewById(R.id.main1_progressbar);

		//			// 사용자 아이디를 꺼낸다.
		sharedPrefCustom = getActivity().getSharedPreferences(CommonConstant.prefName,
				Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);
		userId = sharedPrefCustom.getString("userId", "");
		//			
		// 버튼 리스너
		mainMemberListFriendListBtn.setOnClickListener(new OnClickListener() {		// 친구 목록 버튼
			@Override
			public void onClick(View v) {
				mainMemberlistTitle_1.setVisibility(View.GONE);
				mainMemberlistTitle_2.setVisibility(View.VISIBLE);

				handler.sendEmptyMessage(SELECT_FRIEND_LIST);
			}
		});
		mainMemberListMemberListBtn.setOnClickListener(new OnClickListener() {		// 전체 멤버 목록 버튼
			@Override
			public void onClick(View v) {
				mainMemberlistTitle_2.setVisibility(View.GONE);
				mainMemberlistTitle_1.setVisibility(View.VISIBLE);
				initSearchCondition();
				handler.sendEmptyMessage(SELECT_SEARCH_MEMBER_LIST);		// SELECT_MEMBER_LIST -> SELECT_SEARCH_MEMBER_LIST
			}
		});
		mainMemberListMemberSearchBtn.setOnClickListener(new OnClickListener() {		// 멤버 검색 버튼
			@Override
			public void onClick(View v) {
				Log.d(TAG,"mainMemberListMemberSearchBtn click");
				// start activity for result  하고 결과 받아서 조회할 것. !!
				Intent searchMemberIntent = new Intent(getActivity(), SearchMemberActivity.class);
				startActivityForResult(searchMemberIntent, 5001);
				// --> 일단 보류
			}
		});


		////////////////////////////////pull down list
		// Set a listener to be invoked when the list should be refreshed.
		((PullToRefreshListView) memberListView).setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				// Do work to refresh the list here.
				if(countOne){
					countOne = false;		
					try {
						pullDownRefreshIng = true;				// 기본 로딩바는 보여주지 않기 위함
						new GetDataTask().execute();
					}catch (Exception e) {
						e.printStackTrace();
					} 
				}else{
					Log.d(TAG,"already running..");		 
					((PullToRefreshListView) memberListView).onRefreshComplete();
				}

			}
		});






		if(countOne){
			countOne = false;
			initSearchCondition();
			handler.sendEmptyMessage(SELECT_SEARCH_MEMBER_LIST);		// SELECT_MEMBER_LIST -> SELECT_SEARCH_MEMBER_LIST	// 전체 멤버 목록 불러오기 
		}else{
			Log.d(TAG,"already running..");		 
		}
		return view;
	}




	//	//////////////////////////////////////////////////////////////////////////////////////////////////////
	// pull down list

	private class GetDataTask extends AsyncTask<Void, Void, String[]> {
		@Override
		protected String[] doInBackground(Void... params) {
			// Simulates a background job.
			Log.d(TAG,"GetDataTask");

			if(screenMode==1 || screenMode==3){
				screenMode=1;
				initSearchCondition();
				callResult = pushChatRest.RestSelectSearchMemberList(pushChatMemberParam);
				// 결과 처리
				if(!(callResult.equals("F"))){
					//							pushChatMemberEntriesFn = pushChatRest.getPushChatMemberEntriesFn();
					try {
						JSONArray jsonArray = new JSONArray(callResult);
						int max = jsonArray.length();
						pushChatMemberEntriesFn = new ArrayList<PushChatMember>(max);

						String tmp_memberId = "";
						String tmp_nickName = "";
						String tmp_phoneNumber = "";
						String tmp_email = "";
						String tmp_comment = "";
						String tmp_profileImageUrl = "";
						String tmp_thumbnailUrl = "";
						String tmp_gender = "";
						String tmp_age = "";
						String tmp_countryCode = "";
						String tmp_languageCode = "";
						String tmp_modifyDate = "";
						String tmp_registerDate = "";
						Bitmap tmp_profileImage = null;
						Bitmap tmp_thumbnail = null;

						if(max>0){
							for ( int i = 0; i < max; i++ ){
								JSONObject jsonObj = jsonArray.getJSONObject(i);
								try{
									tmp_memberId = jsonObj.getString("memberId");
								}catch(Exception e){
									tmp_memberId = "";
								}
								try{
									tmp_nickName = jsonObj.getString("nickName");
								}catch(Exception e){
									tmp_nickName = "";
								}
								try{
									tmp_phoneNumber = jsonObj.getString("phoneNumber");
								}catch(Exception e){
									tmp_phoneNumber = "";
								}
								try{
									tmp_email = jsonObj.getString("email");
								}catch(Exception e){
									tmp_email = "";
								}
								try{
									tmp_comment = jsonObj.getString("comment");
								}catch(Exception e){
									tmp_comment = "";
								}
								try{
									tmp_profileImageUrl = jsonObj.getString("profileImageUrl");
									if(tmp_profileImageUrl!=null&&tmp_profileImageUrl.length()>0){
										//								tmp_profileImage = LoadImage(tmp_profileImageUrl);
									}else{
										tmp_profileImage = null;
									}
								}catch(Exception e){
									tmp_profileImageUrl = "";
								}
								try{
									tmp_thumbnailUrl = jsonObj.getString("thumbnailUrl");
									if(tmp_thumbnailUrl!=null&&tmp_thumbnailUrl.length()>0&&!(tmp_thumbnailUrl.equals("null"))){
										tmp_thumbnail = LoadImage(tmp_thumbnailUrl);
										CommonUtil commonUtil = new CommonUtil();
										tmp_thumbnail = commonUtil.getRoundedCornerBitmap(tmp_thumbnail); // 라운딩 처리
									}else{
										tmp_thumbnail = null;
									}
								}catch(Exception e){
									tmp_thumbnailUrl = "";
								}
								try{
									tmp_gender = jsonObj.getString("gender");
								}catch(Exception e){
									tmp_gender = "";
								}
								try{
									tmp_age = jsonObj.getString("age");
								}catch(Exception e){
									tmp_age = "";
								}
								try{
									tmp_countryCode = jsonObj.getString("countryCode");
								}catch(Exception e){
									tmp_countryCode = "";
								}
								try{
									tmp_languageCode = jsonObj.getString("languageCode");
								}catch(Exception e){
									tmp_languageCode = "";
								}
								try{
									tmp_modifyDate = jsonObj.getString("modifyDate");
								}catch(Exception e){
									tmp_modifyDate = "";
								}
								try{
									tmp_registerDate = jsonObj.getString("registerDate");
								}catch(Exception e){
									tmp_registerDate = "";
								}
								pushChatMemberEntriesFn.add(new PushChatMember(tmp_memberId,
										tmp_nickName,
										tmp_phoneNumber,
										tmp_email,
										tmp_comment,
										tmp_profileImageUrl,
										tmp_thumbnailUrl,
										tmp_gender,
										tmp_age,
										tmp_countryCode,
										tmp_languageCode,
										tmp_modifyDate,
										tmp_registerDate,
										tmp_profileImage,
										tmp_thumbnail
								));
							}
						}
					}catch (JSONException e) {
						e.printStackTrace();
					}
				}
				showMemberList();

			}else if(screenMode==2 || screenMode==4){
				screenMode=2;
				// 파라미터 세팅
				PushChatFriend pushChatFriendParam = new PushChatFriend();
				pushChatFriendParam.setPushChatMemberMemberId(userId);

				// 서버 메소드 호출
				if(!isFinished){
					callResult = pushChatRest.RestSelectFriendList(pushChatFriendParam);
					// 결과 처리
					if(!(callResult.equals("F"))){
						//							pushChatFriendEntriesFn = pushChatRest.getPushChatFriendEntriesFn();
						try {
							JSONArray jsonArray = new JSONArray(callResult);
							int max = jsonArray.length();
							pushChatFriendEntriesFn = new ArrayList<PushChatFriend>(max);

							String tmp_idPushChatFriend = "";
							String tmp_memberId = "";
							String tmp_category = "";
							String tmp_registerDate = "";
							String tmp_pushChatMemberMemberId = "";
							String tmp_nickName = "";
							String tmp_comment = "";
							String tmp_profileImageUrl = "";
							String tmp_thumbnailUrl = "";
							String tmp_gender = "";
							String tmp_age = "";
							Bitmap tmp_profileImage = null;
							Bitmap tmp_thumbnail = null;

							if(max>0){
								for ( int i = 0; i < max; i++ ){
									JSONObject jsonObj = jsonArray.getJSONObject(i);
									try{
										tmp_idPushChatFriend = jsonObj.getString("idPushChatFriend");
									}catch(Exception e){
										tmp_idPushChatFriend = "";
									}
									try{
										tmp_memberId = jsonObj.getString("memberId");
									}catch(Exception e){
										tmp_memberId = "";
									}
									try{
										tmp_category = jsonObj.getString("category");
									}catch(Exception e){
										tmp_category = "";
									}
									try{
										tmp_registerDate = jsonObj.getString("registerDate");
									}catch(Exception e){
										tmp_registerDate = "";
									}
									try{
										tmp_pushChatMemberMemberId = jsonObj.getString("pushChatMemberMemberId");
									}catch(Exception e){
										tmp_pushChatMemberMemberId = "";
									}
									try{
										tmp_nickName = jsonObj.getString("nickName");
									}catch(Exception e){
										tmp_nickName = "";
									}
									try{
										tmp_comment = jsonObj.getString("comment");
									}catch(Exception e){
										tmp_comment = "";
									}
									try{
										tmp_profileImageUrl = jsonObj.getString("profileImageUrl");		// ### 
										if(tmp_profileImageUrl!=null&&tmp_profileImageUrl.length()>0){
											//								tmp_profileImage = LoadImage(tmp_profileImageUrl);
											//								tmp_profileImage = commonUtil.getRoundedCornerBitmap(tmp_profileImage); // 라운딩 처리
										}else{
											tmp_profileImage = null;
										}
									}catch(Exception e){
										tmp_profileImageUrl = "";
									}
									try{
										tmp_thumbnailUrl = jsonObj.getString("thumbnailUrl");
										if(tmp_thumbnailUrl!=null&&tmp_thumbnailUrl.length()>0){
											tmp_thumbnail = LoadImage(tmp_thumbnailUrl);
											CommonUtil commonUtil = new CommonUtil();
											tmp_thumbnail = commonUtil.getRoundedCornerBitmap(tmp_thumbnail); // 라운딩 처리
										}else{
											tmp_thumbnail = null;
										}
									}catch(Exception e){
										tmp_thumbnailUrl = "";
									}
									try{
										tmp_gender = jsonObj.getString("gender");
									}catch(Exception e){
										tmp_gender = "";
									}
									try{
										tmp_age = jsonObj.getString("age");
									}catch(Exception e){
										tmp_age = "";
									}
									//						 public ArrayList<PushChatFriend> pushChatFriendEntries = new ArrayList<PushChatFriend>(); 
									//						List<PushChatFriend> pushChatFriendEntriesFn = new ArrayList<PushChatFriend>();
									pushChatFriendEntriesFn.add(new PushChatFriend(
											tmp_idPushChatFriend,
											tmp_memberId,
											tmp_category,
											tmp_registerDate,
											tmp_pushChatMemberMemberId,
											tmp_nickName,
											tmp_comment,
											tmp_profileImageUrl,
											tmp_thumbnailUrl,
											tmp_gender,
											tmp_age,
											tmp_profileImage,
											tmp_thumbnail
									));
								}
							}
						}catch (JSONException e) {
							e.printStackTrace();
						}
						//							pushChatFriendEntriesFn = pushChatFriendEntries; 
					}
					showFriendList();
				}
			}


			countOne = true;		// 다시 호출 되도록 수정..	
			return null;
		}
		@Override
		protected void onPostExecute(String[] result) {
			// Call onRefreshComplete when the list has been refreshed.
			pullDownRefreshIng = false;							// 기본 로딩바 보여주기 상태 초기화. resume 기능으로는 보여지도록.
			((PullToRefreshListView) memberListView).onRefreshComplete();		// 리프레시가 끝났음을....
			super.onPostExecute(result);
		}
	}


	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	



	/**
	 * 멤버 검색 조건 초기화
	 */
	public void initSearchCondition(){
		pushChatMemberParam = new PushChatMember();
		pushChatMemberParam.setMemberId("");
		pushChatMemberParam.setNickName("");
		pushChatMemberParam.setGender("");
		pushChatMemberParam.setAge("");
		pushChatMemberParam.setPersonalityType("");
	}




	/**
	 * 멤버 리스트를 보여준다
	 * showMemberList
	 */
	public void showMemberList(){
		if(getActivity()!=null){
			getActivity().runOnUiThread(new Runnable(){		 
				@Override
				public void run(){
					Message message = handler.obtainMessage();				
					Bundle b = new Bundle();
					b.putInt("showMemberList", 1);
					message.setData(b);
					handler.sendMessage(message);
				}
			});
		}
	}
	/**
	 * 친구 리스트를 보여준다
	 * showFriendList
	 */
	public void showFriendList(){
		if(getActivity()!=null){
			getActivity().runOnUiThread(new Runnable(){		 
				@Override
				public void run(){
					Message message = handler.obtainMessage();				
					Bundle b = new Bundle();
					b.putInt("showFriendList", 1);
					message.setData(b);
					handler.sendMessage(message);
				}
			});
		}
	}


	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


	/**
	 * 러너블. 검색한 멤버 목록을 가져온다. 
	 */
	class RunnableSelectSearchMemberList implements Runnable {
		public void run(){
			new backgroundThreadSelectSearchMemberList().execute();
		}
	}
	/**
	 * backgroundThreadSelectSearchMemberList
	 * 비동기 스레드  검색한 멤버 목록을 가져온다. 
	 * @author blue
	 *
	 */
	public class backgroundThreadSelectSearchMemberList extends AsyncTask<Void, Void, Void>{
		@Override protected void onPostExecute(Void result) {  
		} 
		@Override protected void onPreExecute() {  
		} 
		@Override protected Void doInBackground(Void... params) {  
			Log.d(TAG,"backgroundThreadSelectSearchMemberList");
			
			screenMode = 1;
			
			// 파라미터 세팅
			// 서버 메소드 호출
			if(FragmentHome.restCallCntUp()){
				showPb();
				if(!isFinished){
					callResult = pushChatRest.RestSelectSearchMemberList(pushChatMemberParam);
					// 결과 처리
					if(!(callResult.equals("F"))){
						//							pushChatMemberEntriesFn = pushChatRest.getPushChatMemberEntriesFn();
						try {
							JSONArray jsonArray = new JSONArray(callResult);
							int max = jsonArray.length();
							pushChatMemberEntriesFn = new ArrayList<PushChatMember>(max);

							String tmp_memberId = "";
							String tmp_nickName = "";
							String tmp_phoneNumber = "";
							String tmp_email = "";
							String tmp_comment = "";
							String tmp_profileImageUrl = "";
							String tmp_thumbnailUrl = "";
							String tmp_gender = "";
							String tmp_age = "";
							String tmp_countryCode = "";
							String tmp_languageCode = "";
							String tmp_modifyDate = "";
							String tmp_registerDate = "";
							Bitmap tmp_profileImage = null;
							Bitmap tmp_thumbnail = null;

							if(max>0){
								for ( int i = 0; i < max; i++ ){
									JSONObject jsonObj = jsonArray.getJSONObject(i);
									try{
										tmp_memberId = jsonObj.getString("memberId");
									}catch(Exception e){
										tmp_memberId = "";
									}
									try{
										tmp_nickName = jsonObj.getString("nickName");
									}catch(Exception e){
										tmp_nickName = "";
									}
									try{
										tmp_phoneNumber = jsonObj.getString("phoneNumber");
									}catch(Exception e){
										tmp_phoneNumber = "";
									}
									try{
										tmp_email = jsonObj.getString("email");
									}catch(Exception e){
										tmp_email = "";
									}
									try{
										tmp_comment = jsonObj.getString("comment");
									}catch(Exception e){
										tmp_comment = "";
									}
									try{
										tmp_profileImageUrl = jsonObj.getString("profileImageUrl");
										if(tmp_profileImageUrl!=null&&tmp_profileImageUrl.length()>0){
											//								tmp_profileImage = LoadImage(tmp_profileImageUrl);
										}else{
											tmp_profileImage = null;
										}
									}catch(Exception e){
										tmp_profileImageUrl = "";
									}
									try{
										tmp_thumbnailUrl = jsonObj.getString("thumbnailUrl");
										if(tmp_thumbnailUrl!=null&&tmp_thumbnailUrl.length()>0&&!(tmp_thumbnailUrl.equals("null"))){
											tmp_thumbnail = LoadImage(tmp_thumbnailUrl);
											CommonUtil commonUtil = new CommonUtil();
											tmp_thumbnail = commonUtil.getRoundedCornerBitmap(tmp_thumbnail); // 라운딩 처리
										}else{
											tmp_thumbnail = null;
										}
									}catch(Exception e){
										tmp_thumbnailUrl = "";
									}
									try{
										tmp_gender = jsonObj.getString("gender");
									}catch(Exception e){
										tmp_gender = "";
									}
									try{
										tmp_age = jsonObj.getString("age");
									}catch(Exception e){
										tmp_age = "";
									}
									try{
										tmp_countryCode = jsonObj.getString("countryCode");
									}catch(Exception e){
										tmp_countryCode = "";
									}
									try{
										tmp_languageCode = jsonObj.getString("languageCode");
									}catch(Exception e){
										tmp_languageCode = "";
									}
									try{
										tmp_modifyDate = jsonObj.getString("modifyDate");
									}catch(Exception e){
										tmp_modifyDate = "";
									}
									try{
										tmp_registerDate = jsonObj.getString("registerDate");
									}catch(Exception e){
										tmp_registerDate = "";
									}
									pushChatMemberEntriesFn.add(new PushChatMember(tmp_memberId,
											tmp_nickName,
											tmp_phoneNumber,
											tmp_email,
											tmp_comment,
											tmp_profileImageUrl,
											tmp_thumbnailUrl,
											tmp_gender,
											tmp_age,
											tmp_countryCode,
											tmp_languageCode,
											tmp_modifyDate,
											tmp_registerDate,
											tmp_profileImage,
											tmp_thumbnail
									));
								}
							}
						}catch (JSONException e) {
							e.printStackTrace();
						}
						//							pushChatMemberEntriesFn = pushChatMemberEntries; 
					}
					showMemberList();
				}
				hidePb();		// @@ 
				FragmentHome.restCallCntDown();
			}
			countOne = true;		// 다시 호출 되도록 수정..	
			return null; 
		}
	}

	/**
	 * 러너블. 친구 목록을 가져온다
	 */
	class RunnableSelectFriendList implements Runnable {
		public void run(){
			new backgroundThreadSelectFriendList().execute();
		}
	}
	/**
	 * backgroundThreadSelectFriendList
	 * 비동기 스레드  친구 목록을 가져온다
	 * @author blue
	 *
	 */
	public class backgroundThreadSelectFriendList extends AsyncTask<Void, Void, Void>{
		@Override protected void onPostExecute(Void result) {  
		} 
		@Override protected void onPreExecute() {  
		} 
		@Override protected Void doInBackground(Void... params) {  
			Log.d(TAG,"backgroundThreadSelectFriendList");

			screenMode = 2;

			// 파라미터 세팅
			PushChatFriend pushChatFriendParam = new PushChatFriend();
			pushChatFriendParam.setPushChatMemberMemberId(userId);

			// 서버 메소드 호출
			if(FragmentHome.restCallCntUp()){
				showPb();
				if(!isFinished){
					callResult = pushChatRest.RestSelectFriendList(pushChatFriendParam);
					// 결과 처리
					if(!(callResult.equals("F"))){
						//							pushChatFriendEntriesFn = pushChatRest.getPushChatFriendEntriesFn();
						try {
							JSONArray jsonArray = new JSONArray(callResult);
							int max = jsonArray.length();
							pushChatFriendEntriesFn = new ArrayList<PushChatFriend>(max);

							String tmp_idPushChatFriend = "";
							String tmp_memberId = "";
							String tmp_category = "";
							String tmp_registerDate = "";
							String tmp_pushChatMemberMemberId = "";
							String tmp_nickName = "";
							String tmp_comment = "";
							String tmp_profileImageUrl = "";
							String tmp_thumbnailUrl = "";
							String tmp_gender = "";
							String tmp_age = "";
							Bitmap tmp_profileImage = null;
							Bitmap tmp_thumbnail = null;

							if(max>0){
								for ( int i = 0; i < max; i++ ){
									JSONObject jsonObj = jsonArray.getJSONObject(i);
									try{
										tmp_idPushChatFriend = jsonObj.getString("idPushChatFriend");
									}catch(Exception e){
										tmp_idPushChatFriend = "";
									}
									try{
										tmp_memberId = jsonObj.getString("memberId");
									}catch(Exception e){
										tmp_memberId = "";
									}
									try{
										tmp_category = jsonObj.getString("category");
									}catch(Exception e){
										tmp_category = "";
									}
									try{
										tmp_registerDate = jsonObj.getString("registerDate");
									}catch(Exception e){
										tmp_registerDate = "";
									}
									try{
										tmp_pushChatMemberMemberId = jsonObj.getString("pushChatMemberMemberId");
									}catch(Exception e){
										tmp_pushChatMemberMemberId = "";
									}
									try{
										tmp_nickName = jsonObj.getString("nickName");
									}catch(Exception e){
										tmp_nickName = "";
									}
									try{
										tmp_comment = jsonObj.getString("comment");
									}catch(Exception e){
										tmp_comment = "";
									}
									try{
										tmp_profileImageUrl = jsonObj.getString("profileImageUrl");		// ### 
										if(tmp_profileImageUrl!=null&&tmp_profileImageUrl.length()>0){
											//								tmp_profileImage = LoadImage(tmp_profileImageUrl);
											//								tmp_profileImage = commonUtil.getRoundedCornerBitmap(tmp_profileImage); // 라운딩 처리
										}else{
											tmp_profileImage = null;
										}
									}catch(Exception e){
										tmp_profileImageUrl = "";
									}
									try{
										tmp_thumbnailUrl = jsonObj.getString("thumbnailUrl");
										if(tmp_thumbnailUrl!=null&&tmp_thumbnailUrl.length()>0){
											tmp_thumbnail = LoadImage(tmp_thumbnailUrl);
											CommonUtil commonUtil = new CommonUtil();
											tmp_thumbnail = commonUtil.getRoundedCornerBitmap(tmp_thumbnail); // 라운딩 처리
										}else{
											tmp_thumbnail = null;
										}
									}catch(Exception e){
										tmp_thumbnailUrl = "";
									}
									try{
										tmp_gender = jsonObj.getString("gender");
									}catch(Exception e){
										tmp_gender = "";
									}
									try{
										tmp_age = jsonObj.getString("age");
									}catch(Exception e){
										tmp_age = "";
									}
									//						 public ArrayList<PushChatFriend> pushChatFriendEntries = new ArrayList<PushChatFriend>(); 
									//						List<PushChatFriend> pushChatFriendEntriesFn = new ArrayList<PushChatFriend>();
									pushChatFriendEntriesFn.add(new PushChatFriend(
											tmp_idPushChatFriend,
											tmp_memberId,
											tmp_category,
											tmp_registerDate,
											tmp_pushChatMemberMemberId,
											tmp_nickName,
											tmp_comment,
											tmp_profileImageUrl,
											tmp_thumbnailUrl,
											tmp_gender,
											tmp_age,
											tmp_profileImage,
											tmp_thumbnail
									));
								}
							}
						}catch (JSONException e) {
							e.printStackTrace();
						}
						//							pushChatFriendEntriesFn = pushChatFriendEntries; 
					}
					showFriendList();

				}
				hidePb();		// @@ 
				FragmentHome.restCallCntDown();
			}
			countOne = true;		// 다시 호출 되도록 수정..	
			return null; 
		}
	}

	////////////////////////	onActivityResult	///////////////////////////////////////////////////////////////////////

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Bundle extraBundle;
		if( requestCode == 5001 ) {
			if(resultCode == Activity.RESULT_OK){		// 정상 반환시.
				Log.d(TAG,"RESULT_OK");
				//				Log.d(TAG,"onActivityResult//5001");
				extraBundle = data.getExtras();		// 번들을 반환했으니까 번들을 불러오면 세팅된 값을 가지고 있음.

				pushChatMemberParam = new PushChatMember();
				String searchMemberId = extraBundle.getString("searchMemberId");	 				// 상호명 검색시 파라미터
				String searchNickName = extraBundle.getString("searchNickName");	 			// 업종 선택시 파라미터
				String searchGender = extraBundle.getString("searchGender");	 			// 업종 선택시 파라미터
				String searchAge = extraBundle.getString("searchAge");	 			// 업종 선택시 파라미터
				String searchPersonalityType = extraBundle.getString("searchPersonalityType");	 			// 업종 선택시 파라미터
				Log.d(TAG,"searchMemberId:"+searchMemberId);		
				Log.d(TAG,"searchNickName:"+searchNickName);
				Log.d(TAG,"searchGender:"+searchGender);
				Log.d(TAG,"searchAge:"+searchAge);
				Log.d(TAG,"searchPersonalityType:"+searchPersonalityType);
				pushChatMemberParam.setMemberId(searchMemberId);
				pushChatMemberParam.setNickName(searchNickName);
				pushChatMemberParam.setGender(searchGender);
				pushChatMemberParam.setAge(searchAge);
				pushChatMemberParam.setPersonalityType(searchPersonalityType);
				// 검색 실행..
				handler.sendEmptyMessage(SELECT_SEARCH_MEMBER_LIST);
			}else if(resultCode == Activity.RESULT_CANCELED){
				Log.d(TAG,"RESULT_CANCELED");
			}
		}
	}

	///////////////////////////////////////////////////////////////////////////////////////////////

	// 이미지 처리
	/**
	 * LoadImage
	 *  이미지 URL 에서 이미지 받아온 스트림을 비트맵으로 저장한다
	 *
	 * @param $imagePath
	 * @param
	 * @return bm
	 */
	private Bitmap LoadImage( String $imagePath ) {
		InputStream inputStream = OpenHttpConnection( $imagePath ) ;
		Bitmap bm = BitmapFactory.decodeStream( inputStream ) ;
		return bm;
	}
	/**
	 * OpenHttpConnection
	 *  이미지 URL 에서 이미지 받아와서 스트림으로 저장한다
	 *
	 * @param $imagePath
	 * @param
	 * @return stream
	 */
	private InputStream OpenHttpConnection(String $imagePath) {
		// TODO Auto-generated method stub
		InputStream stream = null ;
		try {
			URL url = new URL( $imagePath ) ;
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection() ;
			urlConnection.setRequestMethod( "GET" ) ;
			urlConnection.connect() ;
			if( urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK ) {
				stream = urlConnection.getInputStream() ;
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			Log.d(TAG,"OpenHttpConnection-"+$imagePath);
			Log.w(TAG,"MalformedURLException");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.w(TAG,"IOException");
		}
		return stream ;
	}


	////////////////////////	Util	///////////////////////////////////////////////////////////////////////	

	/**
	 * returnThis
	 *  컨택스트 리턴한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public Context returnThis(){
		return getActivity();
	}

	/*
	 * 핸들러를 통한 작업.
	 */
	/**
	 * showMsg
	 *  화면에 토스트 띄움 msg 변수에 내용을 넣어서 호출하면 화면에 토스트를 띄운다.
	 *
	 * @param msg
	 * @param
	 * @return
	 */
	public void showMsg(final String msg){		
		if(getActivity()!=null){
			getActivity().runOnUiThread(new Runnable(){	 
				@Override
				public void run(){
					Message message = handler.obtainMessage();				
					Bundle b = new Bundle();
					b.putInt("showToast", 1);
					b.putString("msg", msg);
					message.setData(b);
					handler.sendMessage(message);
				}
			});
		}
	} 

	/**
	 * showResultDialog
	 *  얼럿 띄운다
	 *
	 * @param msg
	 * @param
	 * @return 
	 */
	public void showResultDialog(final String msg){
		if(getActivity()!=null){
			getActivity().runOnUiThread(new Runnable(){	 
				@Override
				public void run(){
					Message message = handler.obtainMessage();				
					Bundle b = new Bundle();
					b.putInt("showAlert", 1);
					b.putString("msg", msg);			// 화면에 보여줄 메시지
					message.setData(b);
					handler.sendMessage(message);
				}
			});
		}
	}
	// 확인을 받는 컨펌 창을 띄운다
	/**
	 * showConfirmDialog
	 *  확인을 받는 컨펌 창을 띄운다
	 *
	 * @param showConfirmCode
	 * @param msg
	 * @return 
	 */
	public void showConfirmDialog(final int showConfirmCode, final String msg){
		if(getActivity()!=null){
			getActivity().runOnUiThread(new Runnable(){		 
				@Override
				public void run(){
					Message message = handler.obtainMessage();				
					Bundle b = new Bundle();
					b.putInt("showConfirm", showConfirmCode);		 
					b.putString("msg", msg);			// 화면에 보여줄 메시지
					message.setData(b);
					handler.sendMessage(message);
				}
			});
		}
	}

	// 중앙 프로그래스바 보임, 숨김
	/**
	 * showPb
	 *  중앙 프로그래스바 가시화한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void showPb(){
		new Thread( 
				new Runnable(){
					public void run(){
						Message message = handler .obtainMessage();
						Bundle b = new Bundle();
						b.putInt( "order" , 1);
						message.setData(b);
						handler .sendMessage(message);
					}
				}
		).start();
	}
	/**
	 * hidePb
	 *  중앙 프로그래스바 비가시화한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void hidePb(){
		new Thread(
				new Runnable(){
					public void run(){
						Message message = handler .obtainMessage();
						Bundle b = new Bundle();
						b.putInt( "order" , 2);
						message.setData(b);
						handler .sendMessage(message);
					}
				}
		).start();
	}

	/**
	 * onResume
	 *  액티비티 리쥼시 닫기 카운터초기화한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	@Override
	public void onResume(){
		super.onResume();
		isFinished = false;
		FragmentHome.app_end = 0;
		Log.d(TAG,"onResume/ screenMode:"+screenMode);
		// screenMode 1 : 전체 목록. 2 : 친구목록. 3 전체목록. refresh필요. 4. 친구목록. refresh 필요
		if(screenMode==3){
			initSearchCondition();
			handler.sendEmptyMessage(SELECT_SEARCH_MEMBER_LIST);		// SELECT_MEMBER_LIST -> SELECT_SEARCH_MEMBER_LIST
		}else if(screenMode==4){
			handler.sendEmptyMessage(SELECT_FRIEND_LIST);
		}
	}

	// 화면을 끄면 pause 가 먹어서 진행되지 않았던 거였음. onPause -> destroy 로 이동시킴
	@Override
	public void onDestroy(){
		isFinished = true;
		super.onDestroy();
	}

}
